#!/usr/bin/env bash

if [[ "$(uname -s)" = 'Darwin' ]]; then
    READLINK=greadlink
else
    READLINK=readlink
fi

SH_FILE_DIR=$(dirname "$(${READLINK} -f "$0")")
PROJECT_DIR=$(dirname "${SH_FILE_DIR}")


export GOPATH=${PROJECT_DIR}/../..


if [[ "${GOOS}" = 'windows' ]]; then
    SET suffix=.exe
fi


rm -f ${GOPATH}/release/pac*
rm -f ${PROJECT_DIR}/proto/*.pb.go

if [[ ! -x ${GOPATH}/bin/dep ]] || [[ ! -x ${GOPATH}/bin/protoc-gen-go ]] ; then
    echo "get dependent tools..."
    if ! ${SH_FILE_DIR}/go-get-tools.sh ; then
        exit 1
    fi
fi

export PATH=${GOPATH}/bin:$PATH


if [[ -e ${PROJECT_DIR}/Gopkg.toml ]] ; then
    echo "dep ensure..."
    ${SH_FILE_DIR}/dep-ensure.sh
else
    echo "dep init..."
    ${SH_FILE_DIR}/dep-init.sh
fi
if [[ ! $? ]] ; then
    exit 1
fi


echo "compile protoBuf..."
if ! protoc --plugin=protoc-gen-go=${GOPATH}/bin/protoc-gen-go \
    --go_out=${PROJECT_DIR}/proto \
    --proto_path ${PROJECT_DIR}/proto \
    ${PROJECT_DIR}/proto/pb.proto ; then
    exit 2
fi

echo "build pac${suffix}..."
go build -o ${GOPATH}/release/pac${suffix}  \
    ${PROJECT_DIR}/main/main.go
